package view;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import controller.*;
import accounts.*;

public class LoginPanel extends JPanel implements KeyListener{
	JLabel userNameLabel=new JLabel("User Name");
	JLabel passwordLabel=new JLabel("Password");
	
	JPanel userNamePanel;
	JPanel passwordPanel;
	JPanel buttonPanel;
	
	JButton submitButton;
	
	JTextField userNameField=new JTextField(20);
	JPasswordField passwordField=new JPasswordField("admin", 20);
	
	public LoginPanel(){
		userNamePanel=new JPanel();
		passwordPanel=new JPanel();
		buttonPanel=new JPanel();
		
		submitButton=new JButton("Submit");
		
		submitButton.addActionListener(new SubmitButtonActionListener());

		userNamePanel.add(userNameLabel);
		userNamePanel.add(userNameField);

		passwordPanel.add(passwordLabel);
		passwordPanel.add(passwordField);
		
		buttonPanel.add(submitButton);
		
		this.setLayout(new GridLayout(3, 1));
		
		this.add(userNamePanel);
		this.add(passwordPanel);
		this.add(buttonPanel);

		userNameField.addKeyListener(this);
		passwordField.addKeyListener(this);
	}

	private class SubmitButtonActionListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			login(userNameField.getText(), new String(passwordField.getPassword()));
		}
	}
	
	private void login(String username, String password){
		Authorization a = ConnectionTester.authenticateLogin(username, password);
		if(a!=Authorization.NONE){
			//passes authorization to Main Gui
			MainFrame.LaunchMainGUI(a);
		}
	}

	@Override
	public void keyPressed(KeyEvent e){
	}

	@Override
	public void keyReleased(KeyEvent e){
		if(e.getKeyCode()==KeyEvent.VK_ENTER){
			this.submitButton.doClick();
		}
	}

	@Override
	public void keyTyped(KeyEvent e){
	}
	
}
